package the.workshop.milktea.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.wisteria.framework.web.QueryResult;
import org.wisteria.framework.web.mvc.service.AbstractSuperService;
import the.broccoli.setting.service.IParamsService;
import the.workshop.milktea.infrastructure.common.CupTypeEnum;
import the.workshop.milktea.infrastructure.common.IceTypeEnum;
import the.workshop.milktea.infrastructure.common.ProductTypeEnum;
import the.workshop.milktea.infrastructure.common.SugarTypeEnum;
import the.workshop.milktea.infrastructure.mapper.TeaProductMapper;
import the.workshop.milktea.infrastructure.model.Product;
import the.workshop.milktea.interfaces.req.ProductListReq;
import the.workshop.milktea.interfaces.resp.IngredientPageResp;
import the.workshop.milktea.interfaces.resp.ProductPageResp;
import the.workshop.milktea.service.dto.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 奶茶产品 服务实现类
 * </p>
 *
 * @author huamu
 * @since 2023-04-01
 */
@Service
public class TeaProductService extends AbstractSuperService<TeaProductMapper, Product>{

    @Resource
    private IParamsService paramsService;

    @Resource
    private IngredientService ingredientService;

    public boolean add(ProductAddDTO dto) {
        Product entity = new Product();
        BeanUtils.copyProperties(dto, entity);

        entity.setCreatedId(dto.getOperatorId());
        entity.setCreatedName(dto.getOperatorName());
        entity.setCreatedTime(new Date());
        entity.setModifiedId(dto.getOperatorId());
        entity.setModifiedName(dto.getOperatorName());
        entity.setModifiedTime(new Date());
        entity.setProductCode(dto.getProductCode());

        if (dto.getIngredientList() != null) {
            entity.setProductIngredient(JSON.toJSONString(dto.getIngredientList()));
        }

        this.baseMapper.insert(entity);
        return true;
    }

    public boolean modify(ProductModifyDTO dto) {
        Product entity = new Product();
        BeanUtils.copyProperties(dto, entity);
        entity.setId(dto.getProductId());
        if (dto.getIngredientList() != null) {
            entity.setProductIngredient(JSON.toJSONString(dto.getIngredientList()));
        }

        entity.setModifiedId(dto.getOperatorId());
        entity.setModifiedName(dto.getOperatorName());
        entity.setModifiedTime(new Date());
        this.baseMapper.updateById(entity);
        return true;
    }

    public QueryResult<ProductPageResultDTO> page(ProductPageDTO condition) {
        if (condition.getPageNum() == null || condition.getPageSize() == null) {
            return null;
        }
        PageHelper.startPage(condition.getPageNum(), condition.getPageSize());
        Page<ProductPageResultDTO> page = this.baseMapper.selectListPage(condition);
        return new QueryResult(page.getTotal(), page.getResult());
    }

    public ProductGetDTO get(Integer id) {
        Product entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return null;
        }
        ProductGetDTO dto = new ProductGetDTO();
        BeanUtils.copyProperties(entity, dto);
        dto.setProductId(entity.getId());
        if (StringUtils.hasText(entity.getProductIngredient())) {
            dto.setIngredientList(JSON.parseArray(entity.getProductIngredient(), ProductIngredientSubDTO.class));
        }

        return dto;
    }

    public List<ProductGetDTO> getList(ProductListReq req) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        if (req.getCategoryId() != null) {
            queryWrapper.eq(Product::getCategoryId, req.getCategoryId());
        }
        if (StringUtils.hasText(req.getProductCode())) {
            queryWrapper.eq(Product::getProductCode, req.getProductCode());
        }
        List<Product> productList = this.baseMapper.selectList(queryWrapper);
        List<ProductGetDTO> dataList = CollectionUtils.isEmpty(productList) ? null : productList.stream().map(this::convertOf).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dataList)) {
            Map<Integer, String> pumpNameMap = new HashMap<>();
            List<IngredientPageResp> list = ingredientService.getList();
            if (!CollectionUtils.isEmpty(list)) {
                pumpNameMap = list.stream().collect(Collectors.toMap(IngredientPageResp::getIngredientId, IngredientPageResp::getPumpName, (a, b) -> b));
            }

            Map<Integer, String> finalPumpNameMap = pumpNameMap;
            dataList.stream().forEach(it -> {
                it.setImgs(paramsService.getValue("tea.images.host") + "/" + it.getImgs());
                it.setCupTypeName(CupTypeEnum.getName(it.getCupType()));
                it.setIceTypeName(IceTypeEnum.getName(it.getIceType()));
                it.setSugarTypeText(SugarTypeEnum.getName(it.getSugarType()) + " " + it.getSugarWeight() + "g");
                it.setProductTypeName(ProductTypeEnum.getName(it.getProductType()));

                if (!CollectionUtils.isEmpty(it.getIngredientList())) {
                    it.getIngredientList().forEach(item -> {
                        item.setPumpName(finalPumpNameMap.get(item.getIngredientId()));
                    });
                }
            });
        }
        return dataList;
    }

    private ProductGetDTO convertOf(Product source) {
        ProductGetDTO target = new ProductGetDTO();
        BeanUtils.copyProperties(source, target);
        target.setProductId(source.getId());
        if (StringUtils.hasText(source.getProductIngredient())) {
            target.setIngredientList(JSON.parseArray(source.getProductIngredient(), ProductIngredientSubDTO.class));
        }
        return target;
    }
}
